package com.lsb.fitnessnutrition

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ContentValues
import android.content.Intent
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.graphics.Color
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.view.get
import androidx.core.view.iterator
import androidx.navigation.Navigation
import kotlinx.android.synthetic.main.activity_list_plan.*
import kotlinx.android.synthetic.main.fragment_input_one_rm.*
import org.tensorflow.lite.examples.classification.R

class ListPlanActivity : AppCompatActivity() {
    @RequiresApi(Build.VERSION_CODES.P)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_list_plan)

        //连接数据库
        val dbHelper=MyDatabaseHelper(this,"PowerStore.db",null,1)
        val db: SQLiteDatabase
        db=dbHelper.writableDatabase

        val cursor: Cursor
        //查询plan_five表
        cursor=db.query("plan_five",null,null,
            null,null,null,"groups",null)
        //计划表的List
        var list=ArrayList<String>()
        if(cursor.moveToFirst()){
            do {
                var str_1:String=cursor.getString(cursor.getColumnIndex("type"))
                var str_2:String=cursor.getString(cursor.getColumnIndex("weight"))
                var str_3:String=cursor.getString(cursor.getColumnIndex("groups"))
                var str_4:String=cursor.getString(cursor.getColumnIndex("status"))
                var str:String=str_1+"   "+str_2+"kg"+"   "+str_3+"   "+str_4
                list.add(str)
                Log.v("data",str)
            }while (cursor.moveToNext())
        }
        Log.v("11",list.toString())
        cursor.close()
        //正则
        val pattern = "..已打卡".toRegex()
        //重写ArrayAdapter中的getView方法，判断包含“已打卡”，则改变背景颜色，赋值list给adapter
        val adapter: ArrayAdapter<String> =
        object : ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,list){
            @SuppressLint("ResourceAsColor")
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val v = super.getView(position, convertView, parent)
                if(pattern.containsMatchIn(getItem(position).toString())){
                    v.setBackgroundColor(R.color.listViewItemColor)
                }
                return v
            }
        }
        list_view.setAdapter(adapter);

        list_view.setOnItemLongClickListener {
                adapterView, view, i, l ->show_dialog(i,view)
        }


    }


    @RequiresApi(Build.VERSION_CODES.P)
    fun show_dialog(i:Int,view: View):Boolean {
        var dialog = AlertDialog.Builder(this)
        dialog.setTitle("Check message")
        dialog.setMessage("Do you really want to check this train?")
        dialog.setPositiveButton("Yes") {
                dialog, id ->
            run {
                Log.v("update",list_view.getItemAtPosition(i).toString())
                //view.setBackgroundColor(Color.CYAN)
                var update_type=list_view.getItemAtPosition(i).toString().split("   ")[0]
                var update_groups=list_view.getItemAtPosition(i).toString().split("   ")[2]
                Log.v("update",update_type)
                //连接数据库
                val dbHelper=MyDatabaseHelper(this,"PowerStore.db",null,1)
                val db: SQLiteDatabase
                db=dbHelper.writableDatabase

                var values= ContentValues()
                values.put("status","已打卡")
                val selectionArgs = arrayOf(update_type,update_groups)
                //有该条训练记录，执行update操作，更新完成状态
                db.update("plan_five",values,"type = ? and groups = ?", selectionArgs);
                //在数据库中更新完记录，刷新当前页面，即重新跳转到当前页面，显示更新效果
/*                val intent= Intent(this,ListPlanActivity::class.java)
                startActivity(intent)*/
                Toast.makeText(
                    MainActivity@ this, "The train has been checked.",
                    Toast.LENGTH_SHORT
                ).show()
                //销毁当前activity
                finish();
                //重新进入该activity
                startActivity(getIntent());
            }

        }
        dialog.setNegativeButton("No") {
                dialog, id ->
            Toast.makeText(MainActivity@this, "not checked.", Toast.LENGTH_SHORT).show()
        }
        dialog.show()
        return true
    }

    @RequiresApi(Build.VERSION_CODES.P)
    fun add_power(view: View) {
        //连接数据库
        val dbHelper=MyDatabaseHelper(this,"PowerStore.db",null,1)
        val db: SQLiteDatabase
        db=dbHelper.writableDatabase

        var cursor: Cursor
        //查询plan表
        cursor=db.query("plan_five",null,null,
            null,null,null,"groups",null)

        if(cursor.moveToFirst()){
            do {
                var status:String=cursor.getString(cursor.getColumnIndex("status"))
                if(status.equals("未打卡")){
                    Toast.makeText(MainActivity@this, "You need to check your train.", Toast.LENGTH_SHORT).show()
                    break
                }
            }while (cursor.moveToNext())
        }

        var squat_rm = ""
        var bench_rm = ""
        var lift_rm = ""

        //如果全部打卡完成，则更新power表和plan表
        if(cursor.isAfterLast){

            //查询power表，得到cursor
            cursor=db.query("power", null,null,
                null,null,null,null,null)
            //执行update操作
            if(cursor.moveToFirst()){
                do {
                    var str_type:String=cursor.getString(cursor.getColumnIndex("type"))
                    var update_rm = cursor.getString(cursor.getColumnIndex("rm")).toInt()
                    var values= ContentValues()
                    if(str_type.equals("bench")){
                        //更新后的1RM
                        bench_rm = (update_rm+3).toString()
                        values.put("rm",(update_rm+3).toString())
                        db.update("power",values,"type = ?", arrayOf("bench"));
                        values.clear()
                        //Toast.makeText(MainActivity@this, "Add bench power success.", Toast.LENGTH_SHORT).show()
                    }
                    else if(str_type.equals("squat")){
                        //更新后的1RM
                        squat_rm = (update_rm+5).toString()
                        values.put("rm",(update_rm+5).toString())
                        db.update("power",values,"type = ?", arrayOf(str_type))
                        values.clear()
                        //Toast.makeText(MainActivity@this, "Add "+str_type+" power success.", Toast.LENGTH_SHORT).show()
                    }
                    else if(str_type.equals("lift")){
                        //更新后的1RM
                        lift_rm = (update_rm+5).toString()
                        values.put("rm",(update_rm+5).toString())
                        db.update("power",values,"type = ?", arrayOf(str_type))
                        values.clear()
                        //Toast.makeText(MainActivity@this, "Add "+str_type+" power success.", Toast.LENGTH_SHORT).show()
                    }
                }while (cursor.moveToNext())
            }

            //更新2.5公斤的训练计划
            updatePlanTwo(squat_rm,bench_rm,lift_rm)


            dbHelper.createTable_plan_five(db)
            //squat train plan
            var values= ContentValues()
            //1
            var str:String
            str="squat"
            values.put("type",str)
            var weight = squat_rm.toInt()*0.75
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","4*7")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()
            //2
            str="squat"
            values.put("type",str)
            weight = squat_rm.toInt()*0.8
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","5*5")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()
            //3
            str="squat"
            values.put("type",str)
            weight = squat_rm.toInt()*0.85
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","7*3")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()

            //bench plan
            //1
            str="bench"
            values.put("type",str)
            weight = bench_rm.toInt()*0.75
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","4*7")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()
            //2
            str="bench"
            values.put("type",str)
            weight = bench_rm.toInt()*0.8
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","5*5")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()
            //3
            str="bench"
            values.put("type",str)
            weight = bench_rm.toInt()*0.85
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","7*3")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()

            //lift plan
            //1
            str="lift"
            values.put("type",str)
            weight = lift_rm.toInt()*0.75
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","4*7")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()
            //2
            str="lift"
            values.put("type",str)
            weight = lift_rm.toInt()*0.8
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","5*5")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()
            //3
            str="lift"
            values.put("type",str)
            weight = lift_rm.toInt()*0.85
            if(weight%5!=0.0){
                val max = weight + (5-weight%5)
                val min = max - 5
                weight = if((weight-min)<(max-weight)) min else max
            }
            values.put("weight",weight)
            values.put("groups","7*3")
            values.put("status","未打卡")
            db.insert("plan_five",null,values)
            values.clear()

            Toast.makeText(MainActivity@this, "Add power success.", Toast.LENGTH_SHORT).show()
            finish();
            startActivity(getIntent());
        }
        cursor.close()
    }

    @RequiresApi(Build.VERSION_CODES.P)
    fun updatePlanTwo(squat_rm:String,bench_rm:String,lift_rm:String)
    {
        //连接数据库
        val dbHelper=MyDatabaseHelper(this,"PowerStore.db",null,1)
        val db: SQLiteDatabase
        db=dbHelper.writableDatabase

        dbHelper.createTable_plan_two(db)
        //squat train plan
        var values= ContentValues()
        //1
        var str:String
        str="squat"
        values.put("type",str)
        var weight = squat_rm.toInt()*0.75
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","4*7")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()
        //2
        str="squat"
        values.put("type",str)
        weight = squat_rm.toInt()*0.8
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","5*5")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()
        //3
        str="squat"
        values.put("type",str)
        weight = squat_rm.toInt()*0.85
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","7*3")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()

        //bench plan
        //1
        str="bench"
        values.put("type",str)
        weight = bench_rm.toInt()*0.75
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","4*7")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()
        //2
        str="bench"
        values.put("type",str)
        weight = bench_rm.toInt()*0.8
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","5*5")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()
        //3
        str="bench"
        values.put("type",str)
        weight = bench_rm.toInt()*0.85
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","7*3")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()

        //lift plan
        //1
        str="lift"
        values.put("type",str)
        weight = lift_rm.toInt()*0.75
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","4*7")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()
        //2
        str="lift"
        values.put("type",str)
        weight = lift_rm.toInt()*0.8
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","5*5")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()
        //3
        str="lift"
        values.put("type",str)
        weight = lift_rm.toInt()*0.85
        if(weight%2.5!=0.0){
            val max = weight + (2.5-weight%2.5)
            val min = max - 2.5
            weight = if((weight-min)<(max-weight)) min else max
        }
        values.put("weight",weight)
        values.put("groups","7*3")
        values.put("status","未打卡")
        db.insert("plan_two",null,values)
        values.clear()

    }


}